package com.fishingwithme.android.ui.screens.my.points

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.fishingwithme.android.R
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.model.PointsRecord
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.CreditRecordsViewModel
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreditRecordScreen(
    navController: NavController,
    viewModel: CreditRecordsViewModel = hiltViewModel()
) {


    val creditRecords = viewModel.creditRecords.collectAsLazyPagingItems()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.credit_all_records)) },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = stringResource(R.string.back)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(AppDimensions.SPACING_16)
        ) {
            if (creditRecords.loadState.refresh is LoadState.Loading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (creditRecords.loadState.refresh is LoadState.Error) {
                val error = (creditRecords.loadState.refresh as LoadState.Error).error
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = error.message ?: stringResource(R.string.error_load_failed),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))
                        Button(onClick = { creditRecords.retry() }) {
                            Text(text = stringResource(R.string.retry))
                        }
                    }
                }
            } else if (creditRecords.itemCount == 0) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(AppDimensions.SPACING_32),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.credit_no_records),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.outline,
                        textAlign = TextAlign.Center
                    )
                }
            } else {
                // Group records by month
                val groupedRecords = groupRecordsByMonth(creditRecords)

                LazyColumn(
                    contentPadding = PaddingValues(AppDimensions.SPACING_16),
                    verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_8) // Reduced space between rows
                ) {
                    groupedRecords.forEach { (month, records) ->
                        // Month header
                        item {
                            Text(
                                text = month,
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = AppDimensions.SPACING_8)
                            )
                            Divider(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(bottom = AppDimensions.SPACING_8),
                                color = MaterialTheme.colorScheme.outlineVariant
                            )
                        }

                        // Records for this month
                        items(
                            count = records.size,
                            key = { index -> records[index].id }
                        ) { index ->
                            CreditRecordItem(records[index])

                            Divider(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = AppDimensions.SPACING_8),
                                color = MaterialTheme.colorScheme.outlineVariant
                            )
                        }
                    }

                    creditRecords.apply {
                        when (loadState.append) {
                            is LoadState.Loading -> {
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(AppDimensions.SPACING_16),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        CircularProgressIndicator()
                                    }
                                }
                            }

                            is LoadState.Error -> {
                                val error = (loadState.append as LoadState.Error).error
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(AppDimensions.SPACING_16),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Column(
                                            horizontalAlignment = Alignment.CenterHorizontally
                                        ) {
                                            Text(
                                                text = error.message
                                                    ?: stringResource(R.string.error_load_failed),
                                                style = MaterialTheme.typography.bodyMedium,
                                                color = MaterialTheme.colorScheme.error
                                            )
                                            Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))
                                            Button(onClick = { retry() }) {
                                                Text(text = stringResource(R.string.retry))
                                            }
                                        }
                                    }
                                }
                            }

                            is LoadState.NotLoading -> {
                                // No action needed when not loading
                            }
                        }
                    }
                }
            }
        }
    }
}

// Helper function to group records by month
private fun groupRecordsByMonth(creditRecords: LazyPagingItems<PointsRecord>): Map<String, List<PointsRecord>> {
    val grouped = mutableMapOf<String, MutableList<PointsRecord>>()

    for (i in 0 until creditRecords.itemCount) {
        creditRecords[i]?.let { record ->
            val month = getMonthFromDateString(record.createdDate)
            if (!grouped.containsKey(month)) {
                grouped[month] = mutableListOf()
            }
            grouped[month]?.add(record)
        }
    }

    // Sort by month (newest first)
    return grouped.toList().sortedByDescending { it.first }.toMap()
}

private fun getMonthFromDateString(dateString: String): String {
    return try {
        val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val date = inputFormat.parse(dateString)
        val outputFormat = SimpleDateFormat("yyyy年MM月", Locale.getDefault())
        outputFormat.format(date ?: Date())
    } catch (e: Exception) {
        dateString
    }
}

@Composable
private fun CreditRecordItem(record: PointsRecord) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = AppDimensions.SPACING_8),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = record.reason,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.Medium
            )

            Text(
                text = formatDate(record.createdDate),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline
            )
        }

        Text(
            text = "+${record.point}",
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
    }
}

private fun formatDate(dateString: String): String {
    return try {
        val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val outputFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val date = inputFormat.parse(dateString)
        outputFormat.format(date ?: Date())
    } catch (e: Exception) {
        dateString
    }
}

// Hilt入口点接口，用于在Composable中获取PreferencesManager
@EntryPoint
@InstallIn(SingletonComponent::class)
interface CreditRecordScreenHiltEntryPoint {
    fun preferencesManager(): PreferencesManager
}